# -*- coding:utf-8 -*-

# @Time : 2022/11/22 15:11
# @Author : 快乐的小猴子
# @Version : 
# @Function :
import os
import conf
import requests
from lxml import etree


class HomePageDatas:
    """ 发送请求数据 """

    def send(self, url):
        resp = requests.get(url, headers=conf.headers)
        resp.encoding = 'utf-8'
        return resp.text

    """ 校验文件路径 """

    def verf_file_path(self, fir_name, sec_name):
        file_path = os.getcwd() + '\\files\\{}\{}\\'.format(fir_name, sec_name)
        if not os.path.exists(file_path):
            os.makedirs(file_path)
        return file_path

    """ 处理首页标题数据 """

    def handle_resp(self, title_name, home_title_url, *args):
        head_snd_names = args[0].xpath('./p/a/text()')
        head_snd_hrefs = args[1].xpath('./p/a/@href')
        map_data_dic = {}
        head_snd_data_list = []
        for i in range(0, len(head_snd_names)):
            head_snd_data_list.append((head_snd_names[i], head_snd_hrefs[i]))
        map_data_dic[title_name] = (home_title_url, head_snd_data_list)
        return map_data_dic

    """ 获取首页标题栏数据 """

    def get_home_head_datas(self, resp):
        et = etree.HTML(resp)
        head_names = et.xpath('//div[@class="header"]/div[3]/div/ul/li[@class="dropdown "]/a/text()')
        head_hrefs = et.xpath('//div[@class="header"]/div[3]/div/ul/li[@class="dropdown "]/a/@href')
        head_snd_names_resp = et.xpath('//div[@class="header"]/div[3]/div/ul/li[@class="dropdown "]/div')
        head_snd_hrefs_resp = et.xpath('//div[@class="header"]/div[3]/div/ul/li[@class="dropdown "]/div')
        home_data_list = []
        for i in range(0, len(head_names)):
            map_data_dic = self.handle_resp(head_names[i], head_hrefs[i], head_snd_names_resp[i],
                                            head_snd_hrefs_resp[i])
            home_data_list.append(map_data_dic)
        return home_data_list

    """ 首页主函数 """

    def home_main(self):
        resp = self.send(conf.url)
        home_data_list = self.get_home_head_datas(resp)
        print('home_data_list: ', len(home_data_list), home_data_list)
        return home_data_list
